import { message } from "ant-design-vue";
import { defineStore } from "pinia";
import type { RouteLocationNormalized } from "vue-router";
import { useMenuStore } from "./menu";
import { MenuItem, MenuType } from "/@/api/aiot/menu/models";
import type { UserLabel } from "/@/api/aiot/projectManage/models";
import { getProjectPermissions } from "/@/api/aiot/projectSetting";
import type { ProjectRoleItem } from "/@/api/aiot/projectSetting/models";
import { getFunctions } from "/@/api/aiot/role";
import { OperPermissionType, RoleFunctionMenuItem, RoleType } from "/@/api/aiot/role/models";
import { AdminRoleType } from "/@/api/aiot/role/models";
import { getUserTenantInfoByUserId } from "/@/api/aiot/user";
import type { UserDetail } from "/@/api/aiot/user/models";
import { RequsetOptons } from "/@/api/req";
import { PROJECT_DETAIL_ROUTE_NAME } from "/@/router";
import authCache from "/@/utils/cache/authCache";
import { findItemByKey, loopItem } from "/@/utils/treeData";

interface UserState {
  detail: UserDetail;
  initDetail: boolean;
  permissions: RoleFunctionMenuItem[];
  projectPermissions: RoleFunctionMenuItem[];
  initPermissons: boolean;
  projectRoleType: ProjectRoleItem["projectRoleType"];
}

// type DetailCallBack = (detail: UserDetail) => void;

// let detailCallBacks: DetailCallBack[] = [];

export const useUserStore = defineStore("user", {
  state: (): UserState => {
    return {
      detail: {
        userTenantInfoVo: {
          nickName: "--",
          phone: "--",
          genderName: "--",
          companyEmail: "--",
          companyName: "",
          userGroups: "--",
          stateName: "--",
          state: "",
          organizationName: "--",
          tenantId: "",
          tenantRoles: [],
          tenantMaxRole: { roleName: "", roleType: "" },
          location: "",
          workViewType: "",
        },
        userVo: {
          userId: "",
          userName: "",
          loginAccount: "",
        },
      },
      initDetail: false,
      permissions: [],
      projectPermissions: [],
      projectRoleType: "TENANT",
      initPermissons: false,
    };
  },
  actions: {
    /**
     * 刷新当前登录用户的用户详细数据
     */
    async reloadCurUserDetail(options: RequsetOptons) {
      const info = authCache.getUserInfo();
      const data = await getUserTenantInfoByUserId(
        info
          ? {
              userId: info.userId,
            }
          : {},
        options
      );
      if (data) {
        this.initDetail = true;
        this.detail = data;
        if (!info) {
          authCache.setUserInfo({
            userId: data.userVo.userId,
            name: data.userVo.userName,
            account: data.userVo.loginAccount,
          });
        }
      }
      return data;
    },
    /**
     * 刷新当前登录用户的功能权限
     */
    async reloadCurUserPermissions(route?: RouteLocationNormalized) {
      const options: RequsetOptons = {
        useGlobalLoading: false,
        useDefaultErrHandle: false,
        useDefaultFailHandle: false,
        autoRedirect: false,
      };
      if (route) {
        const name = route.name as string;
        if (name && name.startsWith(`${PROJECT_DETAIL_ROUTE_NAME}-`)) {
          //需加载项目权限
          const res = await getProjectPermissions(route.params.id as string, options);
          if (res) {
            this.projectRoleType = res.projectRoleType;
            this.projectPermissions = res.projectRolePermissions || [];
          } else {
            return null;
          }
        }
      }
      const permissions = await getFunctions(options);
      if (permissions) {
        this.permissions = permissions;
        this.initPermissons = true;
      } else {
        return null;
      }
    },
    getPermissionByName(routeName: string): RoleFunctionMenuItem | null {
      let parentRouteName = routeName;
      if (routeName.indexOf("-") !== -1) {
        parentRouteName = routeName.split("-")[0];
      }
      const menuStore = useMenuStore();
      if (parentRouteName === PROJECT_DETAIL_ROUTE_NAME) {
        if (this.isProjectLeader()) {
          return {
            operationType: OperPermissionType.MANAGE,
            operationsType: OperPermissionType.MANAGE,
          };
        }
        //项目详情的子页面权限特殊处理
        const data = menuStore.getProjectMenuData();
        const menuItem = data.find((item) => item.functionUrl === routeName);
        if (menuItem) {
          const permission = this.projectPermissions.find((el) => {
            return el.functionId === menuItem.functionId;
          });
          return permission && (permission.operationsType || permission.operationType) ? permission : null;
        }
        return null;
      }
      if (this.isAdmin()) {
        //admin跳过菜单权限
        return {
          operationType: OperPermissionType.MANAGE,
          operationsType: OperPermissionType.MANAGE,
        };
      }
      let menuItem: null | MenuItem = null;
      // console.log("=======>getPermissionByName", parentRouteName, menuStore.menuData);
      loopItem<MenuItem>(menuStore.menuData, (item) => {
        if (item.functionUrl.replace(/^\//, "") === parentRouteName && item.type === MenuType.FUNCTION) {
          menuItem = item;
          return false;
        }
      });
      if (menuItem) {
        const re = this.isMenuItemAuth(menuItem);
        // console.log("===============>getPermissionByName", routeName, (menuItem as MenuItem).functionUrl, !!re);
        return re;
      }
      return null;
    },
    isRouteAuth(routeName: string): boolean {
      const permission = this.getPermissionByName(routeName);
      // const permission = this.getPermissionByAction(action);
      return !!permission;
    },
    //判断菜单权限，注意不是项目详情的菜单
    isMenuItemAuth(item: MenuItem) {
      if (this.isAdmin()) {
        return {
          operationType: OperPermissionType.MANAGE,
          operationsType: OperPermissionType.MANAGE,
        };
      }
      const permission = this.permissions.find((el) => {
        return el.functionId === item.functionId;
      });
      // console.log("==========>isMenuItemAuth", item, permission, this.permissions);
      return permission && permission.operationsType ? permission : null;
    },
    /**
     * 判断当前登录的用户是否平台管理员或是企业管理员角色
     */
    isAdmin() {
      if (this.detail && this.detail.userTenantInfoVo) {
        const maxRole = this.detail.userTenantInfoVo.tenantMaxRole;
        if (!maxRole) return false;
        const type = maxRole.roleType;
        return type === AdminRoleType.system || type === AdminRoleType.tenant;
      }
      return false;
    },
    isAdminType(type?: RoleType | AdminRoleType) {
      return type === AdminRoleType.system || type === AdminRoleType.tenant;
    },
    //是否平台级用户
    isPlatformUser() {
      if (this.detail && this.detail.userTenantInfoVo) {
        const maxRole = this.detail.userTenantInfoVo.tenantMaxRole;
        if (!maxRole) return false;
        return maxRole.roleType === AdminRoleType.system || maxRole.roleType === RoleType.platform;
      }
      return false;
    },
    isProjectLeader() {
      return this.projectRoleType === "LEADER";
    },
  },
});
